const koa = require('koa');
const app = new koa();
const static = require('./applymiddleware/static');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const query = require('./db/index');
let PORT = 3000;

app.use(bodyParser());
app.use(router.routes(), router.allowedMethods());
app.use(static('./public'));

router.post('/getUser', async (ctx, next) => {
    const res = await query('select * from user');
    ctx.body = res;
});

router.post('/addUser', async (ctx, next) => {
    const {name, pwd} = ctx.request.body;
    if(!name || !pwd) return ctx.body = {code: 3, msg: "参数错误"}
    const res = await query(`insert into user (name, pwd) values ('${name}', '${pwd}')`);
    if(res.affectedRows === 1){
        ctx.body = {
            code: 0,
            msg: "添加成功"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "添加失败"
        }
    }
});

router.post('/changeUser', async (ctx, next)=>{
    const { id, name, pwd } = ctx.request.body;
    if(!name || !pwd || !id) return ctx.body = {code: 3, msg: "参数错误"}
    const res = await query(`update user set name='${name}', pwd='${pwd}' where id='${id}'`);
    if(res.affectedRows === 1){
        ctx.body = {
            code: 0,
            msg: "修改成功"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "修改失败"
        }
    }
});


router.post('/delById', async (ctx, next)=>{
    const { id } = ctx.request.body;
    if(!id) return ctx.body = {code: 3, msg: "参数错误"}
    const res = await query(`delete from user where id = ${id}`);
    if(res.affectedRows === 1){
        ctx.body = {
            code: 0,
            msg: "删除成功"
        }
    } else {
        ctx.body = {
            code: 1,
            msg: "删除失败"
        }
    }
});

app.listen(PORT, ()=>{ console.log('启动成功，端口：'+PORT); });